package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.RecommendVoice;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 圈子服务实现类
 * 点赞
 * 喜欢
 * 评论
 */
@Service
public class RecommendVoiceImpl implements RecommendVoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public RecommendVoice queryMessage(Long userId) {
        //1.查询出一条推荐语言动态
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));
        query.addCriteria(Criteria.where("readStatus").is(0));
        query.with(Sort.by(Sort.Order.desc("created ")));
        RecommendVoice recommendVoice = mongoTemplate.findOne(query, RecommendVoice.class);

        if (recommendVoice!=null){
            //2.保证不重复将同一id排除
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("userId").is(recommendVoice.getUserId()).and("toUserId").is(userId));
            List<RecommendVoice> list = mongoTemplate.find(query1, RecommendVoice.class);
            if (!CollectionUtils.isEmpty(list)) {
                for (RecommendVoice voice : list) {
                    Update update = Update.update("readStatus", 1);

                    mongoTemplate.updateMulti(query1, update, RecommendVoice.class);
                }
            }
            return recommendVoice;
        }
        return null;
}
}
